//jQuery 扩展
jQuery.fn.extend({
    scrolling: function(options, func) {
        var defaults = {
            target: 1,
            timer: 1000,
            offset: 0
        };
        func = func || $.noop;
        var o = jQuery.extend(defaults, options || {});
        this.each(function(i) {
            switch (o.target) {
                case 1:
                    var targetTop = jQuery(this).offset().top + o.offset;
                    jQuery("body").animate({
                        scrollTop: targetTop
                    }, o.timer);
                    break;
                case 2:
                    var targetLeft = jQuery(this).offset().left + o.offset;
                    jQuery("body").animate({
                        scrollLeft: targetLeft
                    }, o.timer);
                    break;
            }
            return false;
        });
        return this;
    }
});
var KS = {
    obj: {},
    tools: {
        in_array: function(value, array) {
            //判断是否在数组中
            var i;
            for (i = 0; i < array.length; i++) {
                if (value === array[i]) {
                    return i;
                }
            }
            return false;
        },
        string: {
            //字符串操作
            format: function() {
                if (arguments.length == 0)
                    return "";
                var args = arguments;
                var str = args[0];
                return str.replace(/\{(\d+)\}/gm, function() {
                    return args[parseInt(arguments[1]) + 1];
                });
            },
            length: function(str) {
                var len = 0;
                for (var i = 0; i < str.length; i++) {
                    if (str.charCodeAt(i) >= 0x4e00 && str.charCodeAt(i) <= 0x9fa5) {
                        len += 2;
                    } else {
                        len++;
                    }
                }
                return len;
            }
        },
        bgflash: function(obj) {
            KS.times = KS.times == undefined ? 1 : KS.times;
            if (KS.times > 2) {
                KS.times = 1;
                return false;
            }
            obj.css({
                background: "#ffc8c8"
            }).addClass("Validform_error");
            setTimeout(function() {
                obj.css({
                    background: "#ffffff"
                }).focus();
                KS.times++;
                setTimeout(function() {
                    KS.tools.bgflash(obj);
                }, 200);
            }, 200);
            return false;
        },
        hashString: function(item) {
            //获取中的地址参数
            if (!item)
                return location.hash.substring(1);
            var sValue = location.hash.match(new RegExp("[\#\&]" + item + "=([^\&]*)(\&?)", "i"));
            sValue = sValue ? sValue[1] : "";
            return sValue == location.hash.substring(1) ? "" : sValue == undefined ? location.hash.substring(1) : decodeURIComponent(sValue);
        },
        cookie: function(name, value, options) {
            //COOKIE操作
            if (typeof value != 'undefined') {
                options = options || {};
                if (value === null) {
                    value = '';
                    $.extend({}, options);
                    options.expires = -1;
                }
                var expires = '';
                if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                    var date;
                    if (typeof options.expires == 'number') {
                        date = new Date();
                        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                    } else {
                        date = options.expires;
                    }
                    expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
                }
                var path = options.path ? '; path=' + (options.path) : '';
                var domain = options.domain ? '; domain=' + (options.domain) : '';
                var secure = options.secure ? '; secure' : '';
                document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
            } else {
                var cookieValue = '';
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = cookies[i].trim();
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
        }
    },
    common: {
        module: [],
        isload: function(module) {
            for (var i in KS.common.module) {
                if (module == KS.common.module[i]) {
                    return true;
                }
            }
            return false;
        },
        load: function(module, callback, alwayscallback) {
            if ($.isArray(module)) {
                for (var i = 0; i < module.length; i++) {
                    $.getScript(module[i], function() {
                        if (i == module.length) {
                            if (typeof callback == 'function') {
                                callback.call();
                            }
                        }
                    });
                }
            } else {
                module = module.replace(/_/g, '.');
                try {
                    if (eval("typeof KS." + module) == 'function') {
                        if (!KS.common.isload(module)) {
                            KS.common.module.push(module);
                            eval("KS." + module + "();");
                            if (typeof callback == 'function') {
                                callback.call();
                            }
                        }
                    }
                } catch (error) {
                    console.log(error);
                }
            }
            if (typeof alwayscallback == 'function') {
                $(function() {
                    alwayscallback.call();
                });
            }
        },
        init: function() {
            if ($.browser.msie && $.browser.version < 9.0) {
                $('<div class="alert alert_block" style="margin:0;">您当前使用的浏览器版本(Internet Explorer ' + $.browser.version + ')过低，为了您能正常使用记账家网站提供的功能，请使用<a href="http://www.google.cn/intl/zh-CN/chrome/" target="_blank">Chrome谷歌浏览器</a>或<a href="http://firefox.com.cn/download/" target="_blank">Firefox火狐浏览器</a>登录使用</div>').prependTo($("#main"));
            }
            $("a.close").live("click", function() {
                $(this).closest(".alert").slideUp();
                return false;
            });
            $("#nav > ul > li").live("mouseenter", function() {
                $("ul", this).fadeIn(100);
                $("a:first", this).addClass("hover");
            }).live("mouseleave", function() {
                $("ul", this).hide();
                $("a:first", this).removeClass("hover");
            });

            var i = 0;
            var j = 0;
            var f = '.downlist,.filter';
            $(".dropdown").live("mouseenter", function() {
                var _this = this;
                clearTimeout(j);
                if ($(f, _this)[0]) {
                    $(f).not($(f, _this)[0]).hide();
                } else {
                    $(f).hide();
                }
                i = setTimeout(function() {
                    $(f, _this).show();
                }, 100);
            }).live("mouseleave", function() {
                var _this = this;
                clearTimeout(i);
                j = setTimeout(function() {
                    $(f, _this).hide();
                }, 500);
            });

            $(".datepicker").each(function() {
                $(this).datepicker({
                    container: '',
                    lowerLimit: new Date("2012/01/01")
                });
            });

            //$("[datatype]").live("focus",function(){$(this).removeClass("Validform_error");});
            //$.dialog.alert("姓名不能为空！姓名不能为空！姓名不能为空！姓名不能为空！姓名不能为空！");
            //$.dialog.confirm("确认删除？确认删除");
            $(".del").live("click", function() {
                var _this = this;
                var confirmarr = {
                    "category_delete": "删除分类后,该分类所有子分类也将删除！<br />删除分类并不会删除属于该分类的账目数据！<br />确认删除？",
                    "account_delete": "删除账户并不会删除属于该帐户的账目数据！<br />帐户数据需要手动删除<br />确认删除？"
                };
                var callback = $(this).attr("callback");
                var confirmtxt = $(this).attr("confirm");
                if (!confirmtxt)
                    confirmtxt = callback != undefined && confirmarr[callback] != undefined ? confirmarr[callback] : "确认删除？";
                $.dialog.ask(confirmtxt, {
                    follow: this,
                    yes: function() {
                        KS.loading(true);
                        $.ajax({
                            url: $(_this).attr("href"),
                            dataType: 'json',
                            success: function(ret) {
                                if (ret.code != undefined && ret.code == 0) {
                                    $.dialog.suggest("删除成功！");
                                    if (eval("typeof " + callback) == 'function') {
                                        eval(callback + "(_this);");
                                    } else {
                                        $(_this).closest("tr").fadeOut();
                                    }
                                } else {
                                    var text = ret.result != undefined && ret.result != '' ? ret.result : "删除失败！";
                                    $.dialog.suggest(text);
                                }
                            },
                            complete: function(ret) {
                                KS.loading(false);
                            }
                        });
                    }
                });
                return false;
            });
        },
        editIcon: function() {

        }
    },
    loading: function(state) {
        if (state) {
            $("#loading").css("left", $(window).width() / 2 - 36).show();
        } else {
            $("#loading").hide();
        }
    },
    tabs: function(obj, cobj) {
        obj = obj == undefined ? $(".tabs_t") : $(obj);
        //普通选项卡切换
        obj.each(function() {
            var _this = this;
            if (!$(this).hasClass("tabs_n")) {
                $("ul:eq(0)>li", this).live("hover", function() {
                    var _class = this.className.split(" ");
                    if ($.inArray("none", _class) == -1 && $.inArray("more", _class) == -1) {
                        var _index = $(this).parent().children(":not(.more,.none)").index($(this).addClass("current").siblings().removeClass("current").end()[0]);
                        //var tab_content = $(obj).siblings(cobj);//取消同级参考
                        var tabs_c = cobj == undefined ? $(_this).next(".tabs_b").find(".tabs_c") : $(cobj);
                        if (tabs_c.length > 0)
                            tabs_c.hide().eq(_index).show();
                    }
                });
            }
        });
        //选项卡
        $("ul.tabs_s>li>a").live("hover", function() {
            var _this = $(this).parent();
            var _class = _this[0].className.split(" ");
            if ($.inArray("none", _class) == -1) {
                _this.addClass("curr").siblings().removeClass("curr");
            }
        });
        //Hover事件绑定
        $("ul.tabs_h>li").live("hover", function() {
            var _this = $(this);
            var _class = _this[0].className.split(" ");
            if ($.inArray("none", _class) == -1) {
                _this.addClass("hover").siblings().removeClass("hover");
            }
        });
    },
    tips: function(text, options) {
        options = options || {};
        var opt = {
            container: document.body,
            id: '',
            icon: 'normal',
            left: 0,
            top: 0,
            arrow: 'up',
            loc: 20,
            always: false,
            linktext: '我知道了',
            closebtn: true,
            callback: false
        };
        opt = $.extend(opt, options);
        var id = opt.id == '' ? "tips_" + opt.left + '_' + opt.top + '_' + opt.arrow + '_' + opt.loc : opt.id;
        if (opt.always || KS.tools.cookie('close_' + id) != 1) {
            if ($("#" + id).size() > 0) {
                $("#" + id + ".tipstxt .black").html(text);
                $("#" + id).show();
            }
            else {
                var c = '<div id="' + id + '" class="newtips" style="top: ' + opt.top + 'px; left: ' + opt.left + 'px; ">';
                c = c + '<div class="tipcontainer" style="opacity: 1; ">';
                c = opt.arrow == 'up' ? c + '<span class="arrowup" style="margin-left: ' + opt.loc + 'px; "></span>' : c;
                c = opt.arrow == 'left' ? c + '<span class="arrowleft" style="margin-top: ' + opt.loc + 'px; "></span>' : c;
                c = c + '<div class="t_container t_' + opt.arrow + '"><div class="tcc"><div class="t_content"' + (opt.linktext == '' ? ' style="padding-bottom:15px;"' : '') + '>';
                c = opt.icon != '' ? c + '<div class="tipsicon"><span class="tipsico tipsico_' + opt.icon + '"></span></div>' : c;
                c = opt.closebtn ? c + '<a href="javascript:;" class="t_close t_btnclose"></a>' : c;
                c = c + '<div class="tipstxt' + (opt.icon == '' ? " tipsnoicon" : "") + '"><span class="black">' + text + '</span></div>';
                c = opt.linktext != '' ? c + '<div class="tipsrightpanel"><div class="opertbar"><a class="t_close" href="javascript:;">' + opt.linktext + '</a></div></div>' : c;
                c = c + '<div class="clear"></div>';
                c = c + '</div></div></div>';
                c = opt.arrow == 'down' ? c + '<span class="arrowdown" style="margin-left: ' + opt.loc + 'px; "></span>' : c;
                c = opt.arrow == 'right' ? c + '<span class="arrowright" style="margin-top: ' + opt.loc + 'px; "></span>' : c;
                c = c + '</div></div>';
                $(c).appendTo(opt.container);
            }
            $("#" + id + " .t_close").live("click", function() {
                //关闭层和写Cookie
                $("#" + id).fadeOut();
                if (!opt.always) {
                    KS.tools.cookie('close_' + id, 1, {
                        path: '/',
                        expires: 86400
                    });
                }
                if (opt.callback) {
                    opt.callback();
                }
            });
        }
    },
    statistics: {
        expense: function() {
            $(".selspan a[s][e], .staticsdatefilter a[s][e]").live("click", function() {
                $("input[name=charttitle]").val($(this).attr("title"));
                $(".selspan a.btn_g_s").removeClass("btn_g_s").addClass("btn_w_s");
                $(this).addClass("btn_g_s").removeClass("btn_w_s");
                var s = new Date(parseInt($(this).attr("s")) * 1000);
                var e = new Date(parseInt($(this).attr("e")) * 1000);
                $("#startdate").val(s.getFullYear() + "-" + pad((s.getMonth() + 1), 2) + "-" + pad(s.getDate(), 2));
                $("#enddate").val(e.getFullYear() + "-" + pad((e.getMonth() + 1), 2) + "-" + pad(e.getDate(), 2));
                loadchart();
            });

            $(".op_chart .datepicker").live("click", function() {
                $("input[name=charttitle]").val("指定日期");
                $(".selspan a.btn_g_s").removeClass("btn_g_s").addClass("btn_w_s");
            }).live("change", function() {
                loadchart();
            });
        }
    },
    note: {
        index: function() {
            $(".notelist tr").live("mouseenter", function() {
                $(".editarea", this).show();
            }).live("mouseleave", function() {
                $(".editarea", this).hide();
            });
        }
    },
    table: {
        init: function() {
            //隔行变色
            $("table.list tbody > tr:nth-child(even)").addClass("even");
            //hover事件
            $("table.list:not([class*='form']) tr, table.list:not([class*='form']) tr").hover(function() {
                $(this).addClass("hover");
            }, function() {
                $(this).removeClass("hover");
            });
        }
    },
    user: {
        info: {
        },
        form: function() {
            $(".btn_user_form").live("click", function() {
                var form = $(this).closest("form");
                form.unbind("submit");
                KS.loading(true);
                $.ajax({
                    type: 'post',
                    url: form.attr("action"),
                    data: form.serialize(),
                    dataType: 'json',
                    success: function(ret) {
                        $.dialog.suggest(ret.result);
                        KS.loading(false);
                    },
                    error: function(ret) {
                        KS.loading(false);
                        $.dialog.suggest("修改失败,请重试");
                    }
                });
                return false;
            });
        },
        face: function() {
            $("#bigimg").load(function() {
                KS.common.load(["/res/js/jquery.imgareaselect.js"], function() {
                    KS.user.editFace();
                });
            });
        },
        editFace: function() {
            var imgw, imgh;
            this.preview = function(img, selection) {
                var scale50X = 50 / selection.width;
                var scale50Y = 50 / selection.height;
                var scale30X = 30 / selection.width;
                var scale30Y = 30 / selection.height;
                $('#preimg50').css({
                    width: Math.round(scale50X * imgw) + 'px',
                    height: Math.round(scale50Y * imgh) + 'px',
                    marginLeft: '-' + Math.round(scale50X * selection.x1) + 'px',
                    marginTop: '-' + Math.round(scale50Y * selection.y1) + 'px'
                });
                $('#preimg30').css({
                    width: Math.round(scale30X * imgw) + 'px',
                    height: Math.round(scale30Y * imgh) + 'px',
                    marginLeft: '-' + Math.round(scale30X * selection.x1) + 'px',
                    marginTop: '-' + Math.round(scale30Y * selection.y1) + 'px'
                });
                if ($('#imgpos').length && selection)
                    $('#imgpos').attr('value', selection.x1 + '_' + selection.y1 + '_' + (selection.x2 - selection.x1)).attr('name', 'imgpos');
            }
            if ($('#imgpos').length) {
                imgw = $('#bigimg').width();
                imgh = $('#bigimg').height();
                var _ = $('#imgpos').val().split('_');
                var pos = (_[2] && (_[2] != '0') && (parseInt(_[0]) + parseInt(_[2])) <= imgw && (parseInt(_[1]) + parseInt(_[2])) <= imgh) ? {
                    x1: parseInt(_[0]),
                    y1: parseInt(_[1]),
                    x2: parseInt(_[0]) + parseInt(_[2]),
                    y2: parseInt(_[1]) + parseInt(_[2])
                } : {
                    x1: imgw > imgh ? (imgw - imgh) / 2 + 3 : (imgw == imgh ? 0 : 3),
                    x2: imgw > imgh ? (imgw + imgh) / 2 - 3 : (imgw == imgh ? imgw : imgw - 3),
                    y1: imgw > imgh ? 3 : (imgw == imgh ? (imgh - imgw) / 2 : (imgh - imgw) / 2 + 3),
                    y2: imgw > imgh ? imgh - 3 : (imgw == imgh ? (imgh + imgw) / 2 : (imgh + imgw) / 2 - 3)
                };
                $('#bigimg').imgAreaSelect($.extend(pos, {
                    aspectRatio: '1:1',
                    onSelectChange: this.preview,
                    onInit: this.preview,
                    persistent: true,
                    parent: ".avatar_editor"
                }));
            }
        }
    },
    config: {
    },
    dialog: {
        init: function() {
            //弹框点击取消按钮
            $(".cancel").live("click", function() {
                $(this).parentsUntil(".dialog_box").find(".dialog_close").click();
            });
            //AJAX拉取内容
            $(".dialog,.dialog a").live("click", function() {
                var url = $(this).attr("href");
                if (url.substr(0, 10) == 'javascript' || url == '')
                    return false;
                //避免重复点击产生多次请求事件
                if ($(this).attr("posted") == 'true') {
                    return false;
                } else {
                    $(this).attr("posted", true);
                }
                //当前触发对象
                var _this = this;
                var cache = $(this).attr("cache");
                cache = cache == 'true' || cache == '1' || cache == undefined ? true : false;
                var id = $(this).data('id');
                cache = false;//开发状态始终不缓存
                if (id == undefined) {
                    id = $(this).attr("id") != undefined ? $(this).attr("id") : Date.now();
                    if (cache) {
                        $(_this).data("id", id);
                    }
                }
                var method = $(this).attr("method") != undefined ? $(this).attr("method") : 'add';
                $.dialog.ajax($(this).attr("title"), {
                    id: id,
                    cache: cache
                }, {
                    url: url,
                    data: $(this).attr("data"),
                    timeout: 2000,
                    success: function(ajaxret, dialogobj) {
                        KS.obj[dialogobj.opts.id] = dialogobj;
                        /*
                         $("#"+dialogobj.opts.id).bind("resize", function(){
                         KS.obj[dialogobj.opts.id].resize();
                         });
                         */
                        //日期控件
                        $(".datepicker", dialogobj.dialog).each(function() {
                            $(this).datepicker({
                                container: '',
                                lowerLimit: new Date("2012/01/01")
                            });
                        });
                        KS.editor = $(".xheditor", dialogobj.dialog).xheditor({
                            skin: 'nostyle',
                            tools: 'Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,Align,List,Link,Img,Flash,Hr,Emot,Table,Preview,Fullscreen'
                        });
                        //计算器控件
                        $(".calculator").calculator();
                        //验证提示元素
                        //$("[datatype]",dialogobj.dialog).closest("dd").append($('<div class="Validform_checktip"><span>&nbsp;</span><b></b></div>'));
                        $("[datatype]", dialogobj.dialog).each(function() {
                            var text = $(this).attr("tipmsg");
                            text = text != undefined ? text : "";
                            var classname = text != '' ? 'img img_info_t' : '';
                            $(this).closest("dd").append($('<div class="Validform_checktip"><span class="' + classname + '">&nbsp;</span><b>' + text + '</b></div>'));
                        });
                        //表单绑定验证事件
                        KS.validform = $(".validform").Validform({
                            btnSubmit: ".submit",
                            btnReset: ".reset",
                            tiptype: tiptype,
                            ignoreHidden: true,
                            ajaxPost: true,
                            postonce: true,
                            datatype: {
                                "notequal": function(gets, obj, curform, regxp) {
                                    //参数gets是获取到的表单元素值，obj为当前表单元素，curform为当前验证的表单，regxp为内置的一些正则表达式的引用;
                                    if (gets == $("#" + $(obj).attr("notequal")).val()) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                    //注意return可以返回true 或 false 或 字符串文字，true表示验证通过，返回字符串表示验证失败，字符串作为错误提示显示，返回false则用errmsg或默认的错误提示;
                                }
                            },
                            beforeCheck: function(obj) {
                                if (KS.editor) {
                                    $(".xheditor").text(KS.editor.getSource());
                                }
                            },
                            beforeSubmit: function(obj) {
                                $(".alert[rel='error']", obj).remove();
                                //增加loading状态
                                $(".submit b.icon-ok", obj).addClass("icon-loading");
                            },
                            callback: function(formobj, formret) {
                                if (formret.status != undefined) {
                                    if (formret.status == 'y') {
                                        //验证通过回调事件
                                        KS.dialog.ajaxsuccess(formobj, formret, _this, dialogobj);
                                    } else {
                                        $(".poststate em", formobj).addClass("img img_error_t");
                                        $(".poststate b", formobj).text(formret.info);
                                        $(".poststate", formobj).show();
                                    }
                                } else {
                                    $(".poststate em", formobj).addClass("img img_error_t");
                                    $(".poststate b", formobj).text("操作失败！请重试或刷新页面再试！");
                                    $(".poststate", formobj).show();
                                }
                            }
                        });
                        $(_this).removeAttr("posted");
                    }
                }, this);
                return false;
            });
        },
        ajaxsuccess: function(formobj, formret, btnobj, dialogobj) {
            var close = $(btnobj).attr("close");
            var callback = $(btnobj).attr("callback");
            if (formret.close != undefined) {
                close = fromret.close;
            } else {
                close = close == 'true' || close == '1' ? true : false;
            }
            //移除按钮上的loading小图标
            $(".submit b.icon-ok", formobj).removeClass("icon-loading");
            //提示成功
            $.dialog.suggest("操作成功！");
            //成功状态文本
            var text = formret.info != '' ? formret.info : "操作成功！请关闭或继续操作！";
            $(".poststate em", formobj).removeClass('img_error_t').addClass("img img_success_t");
            $(".poststate b", formobj).text(text);
            $(".poststate", formobj).show();
            //重置表单的元素状态和提示状态
            $(".Validform_checktip span", formobj).removeClass();
            $(".Validform_checktip b", formobj).text('');
            $(".xheditor").html('');
            //判断回调函数并回调
            if (eval("typeof " + callback) == 'function') {
                eval(callback + "(formobj, formret, btnobj, dialogobj);");
            }
            //重置文本框和状态
            KS.validform.resetForm(formobj);
            $("select[name=repeatlist],input[name=borrowdatetime]").remove();
            //5秒后自动隐藏成功状态文本
            setTimeout(function() {
                $(".poststate").fadeOut(100, function() {
                    $("em", this).removeClass();
                    $("b", this).text('');
                });
            }, 5000);
            if (close) {
                dialogobj.close();
            }
        }
    },
    bill: {
        index: function() {
            $(".billpager a").live("click", function() {
                KS.bill.load($(this).attr("page"));
                return false;
            });
            //筛选框改变
            $("#bill input[type=checkbox],.op_chart input[type=checkbox]").live("change", function() {
                var h = $(this).closest(".filter").prev();
                var p = $(this).parent().parent();
                if ($(this).val() == 0) {
                    //全选/全不选
                    $(this).parent().nextAll().find("input[type=checkbox]").attr("checked", $(this).attr("checked"));
                    if ($(this).attr("checked") == true) {
                        h.removeClass("filternow");
                    } else {
                        h.addClass("filternow");
                    }
                } else {
                    $(this).parent().next("ul").find("input").attr("checked", $(this).attr("checked"));
                    var cs = $("input[type=checkbox]:checked:not([value=0])", p).size();
                    var checked = false;
                    if (cs == 0) {
                        checked = false;
                    } else if (cs == $("input[type=checkbox]:not([value=0])", p).size()) {
                        checked = true;
                    } else {
                        checked = false;
                    }
                    if ($(p).hasClass("filter")) {
                        $("input[type=checkbox]:first", p).attr("checked", checked);
                    } else {
                        //二级分类时
                        $(p).prev().find("checked").attr("checked", checked);
                    }
                    h.addClass("filternow");
                }
                $("input#" + $(this).closest("ul").attr("field")).val('');
                if ($(this).closest("ul").hasClass("chartuserfilter")) {
                    loadchart();
                } else {
                    KS.bill.load(1);
                }
                return false;
            });
            //文本框改变
            $("#bill input[type=text]").live("change", function() {
                var h = $(this).closest(".filter").prev();
                $(this).closest("ul").find("a[rel]").removeClass("filternow");
                h.addClass("filternow");
                $("input#" + $(this).closest("ul").attr("field")).val('');
                KS.bill.load(1);
                return false;
            });
            //点击排序
            $(".dropdown a.orderby").live("click", function() {
                $(this).next().hide();
                $(".dropdown a.orderby i:not([field=" + $(this).find("i", this).attr("field") + "])").text('').attr('rel', 0);
                var o = $("i", this);
                if (o) {
                    var field = o.attr("field");
                    var rel = o.attr("rel");
                    var t = '';
                    newrel = 0;
                    if (rel == 0) {
                        t = '↓'
                        newrel = 1;
                    } else if (rel == 1) {
                        t = '↑'
                        newrel = 2;
                    } else {
                        t = '';
                        newrel = 0;
                    }
                    o.text(t).attr("rel", newrel);
                    $("#orderby").val(field + "," + newrel);
                    KS.bill.load(1);
                }
            });
            $(".filter a[rel]").live("click", function() {
                var h = $(this).parent().parent().prev();
                var p = $(this).parent().parent();
                $("a[rel]", p).removeClass("filternow");
                if ($(this).attr("rel") == 0) {
                    h.removeClass("filternow");
                } else {
                    h.addClass("filternow");
                    $(this).addClass("filternow");
                }
                p.find("input").val('');
                $("input#" + $(this).closest("ul").attr("field")).val($(this).attr("rel"));
                KS.bill.load(1);
                return false;
            });
            $(".filter li").live("mouseenter", function() {
                $("ins", this).show();
            }).live("mouseleave", function() {
                if (!$("ins", this).hasClass("show")) {
                    $("ins", this).hide();
                }
            });
            $(".filter ins").live("click", function() {
                $(this).toggleClass("show");
                if ($(this).prev().prev().val() == 0) {
                    if ($(this).hasClass("show")) {
                        $(this).attr("title", "全部收起");
                        $(this).parent().parent().find("ul").show();
                        $(this).parent().parent().find("li ins").addClass("show");
                    } else {
                        $(this).attr("title", "全部展开");
                        $(this).parent().parent().find("ul").hide();
                        $(this).parent().parent().find("li ins").removeClass("show");
                    }
                } else {
                    $(this).parent().next().toggle();
                }
            });
            $(".filter ul li input").live("click", function() {
                var u = $(this).parent().parent();
                var i = u.prev().find("input");

                if ($(this).attr("checked") == true) {
                    if ($("input:checked", u).size() == $("input", u).size()) {
                        i.attr("checked", true);
                    }
                } else {
                    i.attr("checked", false);
                }
            });
            $(".fdate").live("click", function() {
                $(".datefilter input").val($(this).text());
                $(".datefilter input:first").change();
            });
            $(".fcategory").live("click", function() {
                var id = $(this).attr("rel");
                var o = $(".categoryfilter #cf" + id);
                if (o.size() > 0) {
                    $(".categoryfilter input[type=checkbox]").attr("checked", false);
                    $(".categoryfilter ins").removeClass("show");
                    $(".categoryfilter ul").hide();

                    if (o.parent().next().find("li").size() == 0) {
                        var p = o.parent().parent().prev();
                        p.find("input[type=checkbox]").attr("checked", false);
                        $("ins", p).click();
                    }
                    o.attr("checked", true).change();
                }
            });
            $(".faccount").live("click", function() {
                var index = $(this).closest("td").index();
                var table = $(this).closest("table");
                var ul = $("tr th:nth-child(" + (index + 1) + ") ul.filter", table);
                var id = $(this).attr("rel");
                var o = $("input[value=" + id + "]", ul);
                if (o.size() > 0) {
                    $("input[type=checkbox]", ul).attr("checked", false);
                    o.attr("checked", true).change();
                }
            });
        },
        edit: function() {
            //更多设置
            $(".moreup").live("click", function() {
                $(this).next("." + $(this).attr("obj")).toggle();
                $("em", this).toggleClass("up");
            });
            //记账类型变更
            $("input[name='row[type]']").live("click", function() {
                var v = $(this).val();
                $(".m_hide").hide();
                $(".cat_cancel").click();
                $("#m_" + v).show();
            });
            $("input[name='row[repeat]']").live("click", function() {
                if ($(this).attr("checked")) {
                    var repeatlist = $("<select name='repeatlist' class='select' style='width:85px;'></select>").insertAfter($(this).next("label"));
                    $.each(KS.bill.frequency, function(i, j) {
                        $("<option value='" + i + "'>" + j + "</option>").appendTo(repeatlist);
                    });
                } else {
                    $(this).next().next("select").remove();
                }
            });
            //添加分类
            $(".category_add").live("click", function() {
                var type = $(this).attr("type");
                KS.tips("你选择所属的父分类<br /><div class='fatherdata'></div>", {id: 'newtip_category_father_' + type, container: $(".col_two"), arrow: 'down', always: true, left: 164, linktext: '', icon: ''});
                $("#category_father_" + type).appendTo($('#newtip_category_father_' + type + ' .fatherdata'));
                if (!$(this).prev().is("span")) {
                    $(this).before('<span><input type="text" name="cat_name" size="15" class="input" placeholder="新增分类名称" />\n\
<a href="javascript:;" class="btn btn_g_s cat_submit"><span><em>提交</em></span></a> \n\
<a href="javascript:;" class="btn btn_w_s cat_cancel"><span><em>取消</em></span></a></span>');
                    $("input[name=cat_name]").focus();
                } else {
                    $(this).prev().show();
                }
                $(this).hide();
            });
            //分类取消
            $(".cat_cancel").live("click", function() {
                $(this).parent().next().show();
                $(this).parent().remove();
                $(".newtips").hide();
            });
            //分类提交
            $(".cat_submit").live("click", function() {
                var _parent = $(this).parent();
                var _select = _parent.prev();
                var _input = $(this).prev();
                var _father = $("#category_father_" + _parent.next().attr("type"));
                var father_id = $("option:selected", _father).val();
                if (_input.val() == '') {
                    KS.tools.bgflash(_input);
                } else {
                    KS.loading(true);
                    $.ajax({
                        type: "POST",
                        url: "/category/add/",
                        dataType: 'json',
                        data: "name=" + _input.val() + "&type=" + _parent.next().attr("type") + "&father_id=" + father_id,
                        success: function(ret) {
                            KS.loading(false);
                            var option = "<option value='" + ret.data.id + "'>" + ret.data.name + "</option>";
                            console.log(father_id);
                            if (father_id == 0) {
                                _father.append(option);
                                _father.find("option:last").attr("selected", true);
                                _select.append("<optgroup label='" + ret.data.name + "' rel='" + ret.data.id + "'></optgroup>");
                                $.dialog.suggest("添加一级分类成功,请继续添加二级分类!");
                                _input.val('').focus();
                            } else {
                                $("optgroup[rel='" + father_id + "']", _select).append(option);
                                $("optgroup[rel='" + father_id + "']", _select).find("option:last").attr("selected", true);
                                $(".cat_cancel", _parent).click();
                            }
                        }
                    });
                }
            });
            $("#m_borrow input[name=category_id]").live('click', function() {
                var text = $(this).attr("id") == 'c_borrowout' ? '收款日期' : '还款日期';
                $("#c_continue_borrowdate").next().html(text);
            });
            $("#c_continue_borrowdate").live('click', function() {
                if ($(this).attr("checked") == true) {
                    $("<input type='text' class='input datepicker' name='borrowdatetime' id='c_borrowdatetime' size='10' readonly />").insertAfter($(this).next())
                            .datepicker({container: '', lowerLimit: new Date("2012/01/01")});
                } else {
                    $(this).next().next().remove();
                }
            });
        },
        editalway: function() {
            //添加账户
            $(".account_add").each(function() {
                $(this).attr("data", "type=" + $(this).attr("type") + "&domid=" + $(this).prev().attr("id"));
            });
        },
        multi: function() {
            //记账类型变更
            $("select.type").live("change", function() {
                var v = $(this).val();
                var dom = $(this).closest("div.col_multi");
                $(".m_hide", dom).hide();
                $(".cat_cancel", dom).click();
                $(".m_" + v, dom).show();
            });
            $(".validform input,.validform select").attr("ignore", "ignore");
        },
        load: function(page) {
            KS.loading(true);
            $.ajax({
                url: "/bill/list/" + $("#billul li.current").attr("rel") + "/" + page + "/10/",
                data: $(".billform").serialize(),
                success: function(ret) {
                    if (ret.substr(0, 1) == '{') {
                        eval("var obj = " + ret + ";");
                        if (obj != undefined && obj.result != undefined) {
                            $.dialog.alert(obj.result);
                        }
                    } else {
                        $("#bill>table.data>tbody").html(ret);
                    }
                },
                error: function(ret) {
                    $.dialog.alert($(ret.responseText).find("h1").text());
                },
                complete: function(ret) {
                    KS.loading(false);
                }
            });
        },
        params: function(data) {
            if (data.startdate) {
                $("#startdate").val(data.startdate);
                $(".datefilter").prev().addClass("filternow");
            }
            if (data.enddate) {
                $("#enddate").val(data.enddate);
                $(".datefilter").prev().addClass("filternow");
            }
            if (data.account_id) {
                $(".accountfilter input").attr("checked", "");
                $(".accountfilter").prev().addClass("filternow");
                data.account_id = $.isArray(data.account_id) ? data.account_id : [data.account_id];
                $.each(data.account_id, function(i, j) {
                    if (j == -1)
                        return true;
                    $("#af" + j).attr("checked", "checked");
                });
            }
            if (data.category_id) {
                $(".categoryfilter input").attr("checked", "");
                $(".categoryfilter").prev().addClass("filternow");
                data.category_id = $.isArray(data.category_id) ? data.category_id : [data.category_id];
                $.each(data.category_id, function(i, j) {
                    if (j == -1)
                        return true;
                    $("#cf" + j).attr("checked", "checked");
                    if ($("#cf" + j).next().next().is("ins")) {
                        $("#cf" + j).next().next().addClass("show");
                        $("#cf" + j).parent().next().find("input").attr("checked", "checked");
                        $("#cf" + j).parent().next().show();
                    } else {
                        $("#cf" + j).parent().parent().show().prev().find("ins").addClass("show");
                    }
                });
            }
        }
    },
    diary: {
        index: function() {
            $(".star").live("click", function() {
                KS.loading(true);
                var _this = this;
                $.ajax({
                    url: $(this).attr("surl"),
                    dataType: 'json',
                    success: function(ret) {
                        if (ret.code != undefined) {
                            if (ret.code == 0) {
                                if (ret.result == 1) {
                                    $(_this).addClass("star_current");
                                } else {
                                    $(_this).removeClass("star_current");
                                }
                            } else {
                                $.dialog.alert(ret.result);
                            }
                        }
                    },
                    complete: function(ret) {
                        KS.loading(false);
                    }
                });
            });
        }
    },
    budget: {
        index: function() {
            $("#budget_inner>dl>dd>.lp-loading").click(function() {
                if ($.browser.msie && $.browser.version < 9.0) {

                } else {
                    if ($(this).next().css("display") == 'none') {
                        $(".percentage", $(this).next()).each(function() {
                            $(this).easyPieChart({
                                animate: 1000,
                                trackColor: "#e3e3e3",
                                barColor: $(this).attr("data-color")
                            });
                        });
                    }
                }
                $(this).next(".budget_inner_i").slideToggle();
            });
        },
        show: function() {
            $('#budget_inner dl dd:first .percentage').each(function() {
                if ($.browser.msie && $.browser.version < 9.0) {

                } else {
                    $(this).easyPieChart({
                        animate: 1000,
                        trackColor: "#e3e3e3",
                        barColor: $(this).attr("data-color")
                    });
                }
            });
            $("#budget_inner dl dd .load").each(function() {
                $(this).animate({'width': $(this).attr("rel")}, 1000);
            });
        },
        edit: function() {
            $(".copyall").live("click", function() {
                $(this).closest("form").attr("action", "/budget/copy/");
                KS.validform.submitForm();
                return true;
            });
            $(".copyone").live("click", function() {
                var _this = this;
                $.ajax({
                    url: "/budget/copy/" + $(this).attr("rel"),
                    type: 'POST',
                    dataType: 'json',
                    success: function(formret) {
                        if (formret.status != undefined) {
                            if (formret.status == 'y') {
                                //验证通过回调事件
                                budget_callback();
                                if (formret.data != undefined && formret.data != null) {
                                    $(_this).parent().prev().find("input").val(formret.data);
                                }
                                $.dialog.suggest(formret.info);
                            } else {
                                $.dialog.suggest(formret.info);
                            }
                        } else {
                            $.dialog.suggest("操作失败！请重试或刷新页面再试！");
                        }
                    }
                });
            });
            $(".clearone").live("click", function() {
                var _this = this;
                $.ajax({
                    url: "/budget/clear/" + $(this).attr("rel"),
                    type: 'POST',
                    dataType: 'json',
                    success: function(formret) {
                        if (formret.status != undefined) {
                            if (formret.status == 'y') {
                                //验证通过回调事件
                                budget_callback();
                                if (formret.data != undefined && formret.data != null) {
                                    $(_this).parent().prev().find("input").val(formret.data);
                                }
                                $.dialog.suggest(formret.info);
                            } else {
                                $.dialog.suggest(formret.info);
                            }
                        } else {
                            $.dialog.suggest("操作失败！请重试或刷新页面再试！");
                        }
                    }
                });
            });
        }
    },
    bbs: {
        index: function() {

        },
        show: function() {
            //发表评论
            $("#normalreply").live("submit", function() {
                var _this = this;
                var content = $("textarea[name=content]", this);
                if (content.val() == '') {
                    KS.tools.bgflash(content);
                } else {
                    //避免重复点击产生多次请求事件
                    if ($(_this).attr("posted") == 'true') {
                        return false;
                    } else {
                        $(_this).attr("posted", true);
                    }
                    KS.loading(true);
                    $(".btn_g_s b.icon", _this).addClass("icon-loading");
                    $.ajax({
                        url: $(this).attr("action"),
                        data: $(this).serialize(),
                        type: 'post',
                        success: function(ret) {
                            reply_callback();
                            $(".btn_w_s", _this).click();
                        },
                        error: function(ret) {
                            $.dialog.alert($(ret.responseText).text());
                        },
                        complete: function(ret) {
                            $(".btn_g_s b.icon", _this).removeClass("icon-loading");
                            KS.loading(false);
                            $(_this).removeAttr("posted");
                        }
                    });
                }
                return false;
            });
        }
    },
    family: {
        index: function() {
            $(".itemlist").live("mouseenter", function() {
                $(".editarea", this).show();
            }).live("mouseleave", function() {
                $(".editarea", this).hide();
            });
            $("#joinfamily").live("click", function() {
                if ($("#familyuuid").val() != '') {
                    $.getJSON("/family/join/" + $("#familyuuid").val(), function(ret) {
                        if (typeof ret.code != 'undefined') {
                            if (ret.code == 0) {
                                $.dialog.suggest("成功加入家庭组");
                                family_callback();
                            } else {
                                $.dialog.suggest(ret.result);
                            }
                        }
                    });
                } else {
                    KS.tools.bgflash($("#familyuuid"));
                }
            });
            $(".generalcode").live("click", function() {
                $.getJSON("/family/get_uuid/", function(ret) {
                    if (typeof ret.code != 'undefined') {
                        $("#uuid").val(ret.result);
                    }
                });
            });
            code = new ZeroClipboard.Client();
            code.setText($("#fid").val());
            code.setHandCursor(true);
            code.glue("copyfidspan", "copyfid");
            code.addEventListener('complete', function(client, text) {
                $.dialog.suggest("复制成功!");
            });
        }
    },
    category: {
        index: function() {
            $("a.light").live("click", function() {
                var _this = this;
                var state = $(_this).hasClass("lightoff") ? 1 : 0;
                var tr = $(_this).closest("tr");
                KS.loading(true);
                $.ajax({
                    url: "/category/light/" + $(_this).closest("tr").attr("cid") + "/" + state,
                    dataType: 'json',
                    success: function(ret) {
                        if (ret.code != undefined && ret.code == 0) {
                            $(_this).toggleClass("lightoff");
                            if (tr.attr("father_id") == "0") {
                                if (state == 1) {
                                    $("tr[father_id='" + tr.attr("cid") + "'] td a.light").removeClass("lightoff");
                                } else {
                                    $("tr[father_id='" + tr.attr("cid") + "'] td a.light").addClass("lightoff");
                                }
                            } else {
                                if (state == 1) {
                                    $("tr[cid='" + tr.attr("father_id") + "'] td a.light").removeClass("lightoff");
                                }
                            }
                            $.dialog.suggest("操作成功!");
                        } else {
                            $.dialog.suggest("操作失败!请重试!");
                        }
                    },
                    error: function() {
                        $.dialog.suggest("操作失败!请重试!");
                    },
                    complete: function() {
                        KS.loading(false);
                    }
                });
            });
            $(".itedit").live("click", function() {
                var p = $(this).parent();
                var pp = p.parent();
                var c = $(this).attr("color");
                p.hide();
                pp.append('<span><a href="javascript:;" class="btn btn_' + c + '_s edit_submit"><span><em>提交</em></span></a> \n\
<a href="javascript:;" class="btn btn_w_s edit_cancel"><span><em>取消</em></span></a></span>');
                var t = pp.siblings("td.tl");
                t.html('<input type="text" class="input edit_name" size="8" value="' + t.text() + '" oldvalue="' + t.text() + '" />');
            });
            $(".edit_cancel, .edit_submit").live("click", function() {
                var p = $(this).parent();
                p.prev().show();
                var td = p.parent().siblings("td.tl");
                p.remove();
                var tr = td.parent();
                var i = $(".edit_name", td);
                if ($(this).hasClass("edit_cancel") || i.val() == i.attr("oldvalue")) {
                    td.text(i.attr("oldvalue"));
                } else {
                    var data = {id: tr.attr("cid"), name: i.val()};
                    $.ajax({
                        type: 'POST',
                        url: '/category/edit/',
                        data: data,
                        dataType: 'json',
                        success: function(ret) {
                            td.text(data.name);
                        }
                    });
                }
            });
        }
    },
    account: {
        index: function() {
            $(".itemlist").live("mouseenter", function() {
                $(".editarea", this).show();
            }).live("mouseleave", function() {
                $(".editarea", this).hide();
            });
        },
        edit: function() {
            $("#number").live("blur", function() {
                if ($("#name").val() == '') {
                    $("#name").val($("#bank_id option:selected").text() + $(this).val());
                }
            });
            $("#type").live("change", function() {
                $("dl[rel],div.warmtips").hide();
                $("dl[rel*='" + $(this).val() + "'],div.warmtips[rel*='" + $(this).val() + "']").show();
                var objid = $(this).closest(".dialog_box").attr("id");
                KS.obj[objid].resize();
            });
            $("#billdatelast,#repaydatelast").live("click", function() {
                if ($(this).attr("checked") == true) {
                    $(this).prev().hide();
                    cssstyle($(this).siblings(".Validform_checktip"), 2);
                    $(this).siblings(".Validform_checktip").find("b").html('');
                    KS.validform.find($("#abce")).ignore("#" + $(this).prev().attr("id"));
                } else {
                    $(this).prev().show();
                    $(this).siblings(".Validform_checktip").find("span").removeClass();
                    $(this).siblings(".Validform_checktip").find("b").html('');
                }
            });
        }
    },
    task: {
        index: function() {

        }
    },
    pjax: {
        init: function() {
            //支持pjax的话使用,不支持的话使用AJAX处理
            if ($.pjax.util.support.pjax) {
                $('#primary').bind('pjax.start', function() {
                    KS.loading(true);
                });
                $('#primary').bind('pjax.end', function(ret) {
                    KS.loading(false);
                    $("#primary .datepicker").each(function() {
                        $(this).datepicker({
                            container: '',
                            lowerLimit: new Date("2012/01/01")
                        });
                    });

                });
                $.pjax({
                    selector: '.ajax[href]:not([output]),.ajax:not([output]) a[href][class!=dialog]', //匹配的元素
                    container: '#primary', //内容替换的容器
                    show: '', //展现的动画
                    cache: false, //是否使用缓存
                    storage: true, //是否使用本地存储
                    titleSuffix: ' - 记账家', //标题后缀
                    filter: function() {
                        var url = $(this).attr("href");
                        if (url.substr(0, 10) == 'javascript' || url == '')
                            return true;
                    },
                    callback: function() {
                    }
                });
                obj = ".ajax[href][output],.ajax[output] a";
            } else {
                obj = ".ajax[href],.ajax a[href][class!=dialog]";
            }
            $(obj).live("click", function() {
                var _this = this;
                var url = $(this).attr("href");
                if (url == undefined)
                    return false;
                var output = $(this).attr("output");
                if (output == undefined) {
                    output = $(this).parent().attr("output");
                    if (output == undefined) {
                        output = '#primary';
                    }
                }
                if (url.substr(0, 10) == 'javascript' || url == '')
                    return false;
                KS.loading(true);
                $.ajax({
                    url: url,
                    success: function(ret) {
                        if (ret.substr(0, 1) == '{') {
                            eval("var obj = " + ret + ";");
                            if (obj != undefined && obj.result != undefined) {
                                $.dialog.alert(obj.result);
                            }
                        } else {
                            $(output).html(ret);
                            if (!$(_this).parent().parent().parent().hasClass('tabs_t')) {
                                $(output).scrolling({
                                    timer: 0,
                                    offset: -40
                                });
                            }
                        }
                    },
                    error: function(ret) {
                        $.dialog.alert($(ret.responseText).find("h1").text());
                    },
                    complete: function(ret) {
                        KS.loading(false);
                    }
                });
                return false;
            });
        }
    }
};

function tiptype(msg, o, cssctl) {
    //msg：提示信息;
    //o:{obj:*,type:*,curform:*}, obj指向的是当前验证的表单元素（或表单对象），
    //type指示提示的状态，值为1、2、3、4， 1：正在检测/提交数据，2：通过验证，3：验证失败，4：提示ignore状态, curform为当前form对象;
    //cssctl:内置的提示信息样式控制函数，该函数需传入两个参数：显示提示信息的对象 和 当前提示的状态（既形参o中的type）;
    //验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象;
    if (!o.obj.is("form")) {
        var objtip = o.obj.siblings(".Validform_checktip");
        //cssctl(objtip,o.type);
        cssstyle(objtip, o.type);
        msg = o.type == 1 || o.type == 2 ? '' : msg;
        objtip.find("b").html(msg);
    } else {
        if (o.type == 3) {
            $(".submit b.icon-ok", o.obj).removeClass("icon-loading");
            $(".col_box", o.obj).prepend("<div class='alert alert_block' rel='error'>提交数据失败！请注意保存数据然后刷新重试！</div>")
        }
    }
}
//validform表单验证样式
function cssstyle(obj, status) {
    obj = obj.find("span");
    obj.removeClass("img_info_t");
    switch (status) {
        case 1:
            obj.removeClass("img_success_t img_error_t").addClass("img img_loading");//checking;
            break;
        case 2:
            obj.removeClass("img_error_t img_loading").addClass("img img_success_t");//passed;
            break;
        case 4:
            obj.removeClass("img_success_t img_error_t img_loading").addClass("img img_warning_t");//for ignore;
            break;
        default:
            obj.removeClass("img_success_t img_loading").addClass("img img_error_t");//wrong;
    }
}
function loadchart() {
    $.ajax({
        url: "/statics/expense",
        type: 'POST',
        dataType: 'html',
        data: $("#expenseform").serialize(),
        success: function(ret) {
            $("#expensechart").html(ret);
        }
    });
}
/* 查表法(完善版本)  by aimingoo */
pad = function(tbl) {
    return function(num, n) {
        return (0 >= (n = n - num.toString().length)) ? num : (tbl[n] || (tbl[n] = Array(n + 1).join(0))) + num;
    }
}([]);
$(function() {
    KS.common.init();//通用
    KS.tabs();//选项卡
    KS.table.init();//表格
    KS.dialog.init();//弹出框
    KS.pjax.init();//PJAX
    //console.log('done@' + new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getSeconds());
});